package org.nanhill.support.hibernate.search;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.nanhill.commons.pattern.search.SearchException;

/**
 * @author alin [xalinx at gmail dot com]
 * @date 2006-10-27
 * 
 * Abstract Hibernate implementation of AbstractSearchVisitor specific.
 */

public abstract class CriteriaSearchVisitor extends HibernateSearchVisitor {
	/**
	 * The Criteria object that the visitor will build up.
	 */
	private DetachedCriteria detachedCriteria;

	protected Criteria criteria;

	public CriteriaSearchVisitor() {
	}

	public CriteriaSearchVisitor(int start, int size) {
		super(start, size);
	}

	/**
	 * Creates an instance of this class, using the session to initialize the
	 * Criteria.
	 * 
	 * @param session
	 *            The session used to initialize the Criteria
	 */
	public CriteriaSearchVisitor(Class entityClz) {
		this.detachedCriteria = DetachedCriteria.forClass(entityClz);
	}

	public CriteriaSearchVisitor(Class entityClz, int start, int size) {
		this(entityClz);
		setStart(start);
		setSize(size);
	}

	public CriteriaSearchVisitor(Session session, int start, int size) {
		super(session, start, size);
	}

	public CriteriaSearchVisitor(Session session) {
		super(session);
	}

	public CriteriaSearchVisitor(Session session, Class entityClz, int start,
			int size) {
		super(session, start, size);
		this.detachedCriteria = DetachedCriteria.forClass(entityClz);
	}

	@Override
	protected void buildQuery() throws SearchException {
		criteria = detachedCriteria.getExecutableCriteria(getSession());
		if (start > 0) {
			criteria.setFirstResult(start);
		}
		if (size > 0) {
			criteria.setMaxResults(size);
		}
	}

	protected DetachedCriteria createCriteria(String name) {
		return detachedCriteria.createCriteria(name);
	}

	protected void addOrder(Order order) {
		detachedCriteria.addOrder(order);
	}

}
